import { nextTick, ref } from 'vue'

export function useScroll () {
  const scrollRef = ref()

  const scrollToBottom = async () => {
    await nextTick()
    if (scrollRef.value) {
      scrollRef.value.setScrollTop(scrollRef.value?.wrapRef?.scrollHeight || 0)
    }
  }

  const scrollToTop = async () => {
    await nextTick()
    if (scrollRef.value) scrollRef.value.setScrollTop(0)
  }

  const scrollToBottomIfAtBottom = async () => {
    await nextTick()
    console.log('==scrollToBottomIfAtBottom-scrollRef', scrollRef)
    if (scrollRef.value) {
      const scrollHeight = scrollRef.value?.wrapRef?.scrollHeight || 0
      const threshold = 100
      const distanceToBottom =
        scrollHeight -
        scrollRef.value?.wrapRef?.scrollTop -
        scrollRef.value?.wrapRef?.clientHeight
      if (distanceToBottom <= threshold) {
        scrollRef.value.setScrollTop(scrollHeight)
      }
    }
  }

  return {
    scrollRef,
    scrollToBottom,
    scrollToTop,
    scrollToBottomIfAtBottom
  }
}
